package com.crm.system.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.DataResponse;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.DhResponse;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.activityManager.CustomerProductActivityQO;
import com.crm.model.qo.sys.UserAccountQO;
import com.crm.model.vo.systemManager.UserAccountImportVO;
import com.crm.model.vo.user.UserAccountAddQO;
import com.crm.model.vo.user.UserAccountManagerVO;
import com.crm.model.vo.user.UserAccountVO;
import com.crm.system.service.cluePoolManager.ExcelUtil;
import com.crm.system.service.user.UserAccountService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author WangFei
 * @date 2020/12/21 15:26
 */
@RestController
@RequestMapping("/account")
@CrossOrigin(origins = "*", maxAge = 3600)
@Slf4j
public class UserAccountController {

    @Autowired
    UserAccountService userAccountService;

    /**
     * 根据部门id获取账号列表
     *
     * @param request
     * @return
     */
    @GetMapping("/getAccountListByDeptId")
    public DataResponse getAccountListByDeptId(HttpServletRequest request, @RequestParam String deptId) {
        List<HashMap> accountVOS = userAccountService.selectUserAccountByDeptId(deptId);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), accountVOS);
    }

    /**
     * 根据公司id获取账号列表
     *
     * @param request
     * @return
     */
    @GetMapping("/getAccountListByCompanyId")
    public DataResponse getAccountListByCompanyId(HttpServletRequest request, @RequestParam String companyId) {
        List<UserAccount> userAccounts = userAccountService.selectUserAccountByCompanyId(companyId);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), userAccounts);
    }

    /**
     * 根据公司id获取账号列表
     *
     * @param request
     * @return
     */
    @GetMapping("/getAccountByCompanyIdExcludeLoginPerson")
    public DataResponse getAccountByCompanyIdExcludeLoginPerson(HttpServletRequest request, @RequestParam String companyId) {
        List<UserAccount> userAccounts = userAccountService.getAccountByCompanyIdExcludeLoginPerson(companyId);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), userAccounts);
    }

    /**
     * 根据公司id获取分页的账号列表
     *
     * @param request
     * @return
     */
    @PostMapping("/getAccountListPageByCompanyId")
    public DataResponse getAccountListPageByCompanyId(HttpServletRequest request,
                                                      @RequestParam(value = "pageIndex", required = false) Integer pageIndex,//页码
                                                      @RequestParam(value = "pageSize", required = false) Integer pageSize,//分页大小
                                                      UserAccountQO userAccountQO) {
        List<UserAccount> userAccounts = userAccountService.getAccountListPageByCompanyId(pageIndex,pageSize,userAccountQO.getCompanyId(),userAccountQO.getUserName());
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), userAccounts);
    }


    /**
     * 根据公司id获取在职且未禁用账号列表
     * @Author renshaorong
     * @Date 2021/7/13
     */
    @GetMapping("/getAbleAccountListByCompanyId")
    public DataResponse getAbleAccountListByCompanyId(HttpServletRequest request, @RequestParam String companyId) {
        List<UserAccountManagerVO> userAccounts = userAccountService.getAbleAccountListByCompanyId(companyId);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), userAccounts);
    }

    /**
     * @Description:合同管理-合作开发人员
     * @Param: * @param
     * @Author: luojie
     * @Date: 2021/3/16 11:44
     */
    @GetMapping("/getAllCoDeveloper")
    public DataResponse getAllCoDeveloper() {
        List<UserAccountVO> userAccountVOList = userAccountService.getAllCoDeveloper();
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), userAccountVOList);
    }



    /**
     * 获取权限组名单添加人员账号列表
     *
     * @param request
     * @return
     */
    @PostMapping("/getPermissionAccountList")
    public DataResponse getPermissionAccountList(HttpServletRequest request,
                                                 @RequestParam(value = "permissionGroupId", required = false) String permissionGroupId) {
        try {
            if (!StringUtils.isBlank(permissionGroupId)) {
                List<Map<String, Object>> userAccountList = userAccountService.selectUserAccountList(permissionGroupId);
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), JSON.toJSON(userAccountList));
            }
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        } catch (Exception e) {
            log.error("UserAccountController getPermissionAccountList error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 获取所有账号
     *
     * @param request
     * @return {@link {com.crm.common.model.DataResponse}}
     * @Author pym
     * @Date 2021/3/17 10:10
     */
    @GetMapping("/getAllAccountList")
    public DataResponse getAllAccountList(HttpServletRequest request) {
        List<UserAccount> userAccounts = userAccountService.getAllAccountList();
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), userAccounts);
    }


    /**
     * @Description: 获取分公司下的账号列表
     * @Param: [request]
     * @Return: com.crm.common.model.DataResponse
     * @Author: lixq-f
     * @Date: 2021/6/28
    **/
    @GetMapping("/getAccountsByCompanyId")
    public DataResponse getAccountListByCompanyId(HttpServletRequest request) {
        List<UserAccount> userAccounts = userAccountService.getAccountListByCompanyId();
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), userAccounts);
    }




    /**
     * 验证原密码是否正确
     *
     * @param oldPassword 当前密码
     * @return
     * @Author renshaorong
     * @Date 2021/3/30
     */
    @PostMapping("/oldPasswordValidate")
    public DataResponse oldPasswordValidate(@RequestParam(value = "oldPassword", required = true) String oldPassword) {
        return userAccountService.verifyPassword(oldPassword) ? new DhResponse(ResponseCodeEnum.OK.getResponseCode()) : new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
    }

    /**
     * 修改用户密码
     *
     * @param userPassword 新密码
     * @param oldPassword  旧密码
     * @return 是否修改成功
     * @Author renshaorong
     * @Date 2021/3/30
     */
    @PostMapping("/resetPassword")
    public DataResponse resetPassword(@RequestParam(value = "userPassword", required = true) String userPassword,
                                      @RequestParam(value = "oldPassword", required = true) String oldPassword) {
        Short result = userAccountService.updateUserPassword(userPassword, oldPassword);//1：成功 2：原密码输入错误 3：密码验证不通过
        if ( (short)1 == result){
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        } else if ((short)2 == result){
            return new DhResponse("PSW001");
        } else if((short)3 == result){
            return new DhResponse("PSW002");
        } else {
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 获取账号列表
     * @Author renshaorong
     * @Date 2021/4/7
     * @param pageIndex 页码
     * @param pageSize 分页大小
     * @param userAccountQO 查询实体
     * @param sortName 排序列名称
     * @param sortOrder 排序规则(asc/desc)
     * @return
     */
    @PostMapping("/selectUserAccountPage")
    public DataResponse selectUserAccountPage(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                              @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                              @RequestParam(value = "sortName", required = false) String sortName,//排序列名字
                                              @RequestParam(value = "sortOrder", required = false) String sortOrder,//排序规则(asc/desc)
                                              UserAccountQO userAccountQO) {
        DhPageInfo<UserAccountManagerVO> UserAccountManagerVOList = userAccountService.selectUserAccountPage(pageIndex,pageSize,userAccountQO,sortName,sortOrder);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),UserAccountManagerVOList);
    }

    @PostMapping("/moveData")
    public DataResponse moveData(){
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),null);
    }

    /**
     * 初始化密码为初始值
     * @Author renshaorong
     * @Date 2021/4/8
     * @param accountId user_account表主键
     * @return
     */
    @GetMapping("initialPassword")
    public DataResponse initialPassword(@RequestParam(value = "accountId") String accountId){
        return userAccountService.initialPassword(accountId) ? new DhResponse(ResponseCodeEnum.OK.getResponseCode()) : new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
    }

    /**
     * 根据主键id获取用户信息，id为空时使用当前登陆用户
     * @Author renshaorong
     * @Date 2021/4/21
     * @param accountId
     * @return
     */
    @GetMapping("selectUserAccountByAccountId")
    public DataResponse selectUserAccountByAccountId(@RequestParam("accountId") String accountId){
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),userAccountService.selectUserAccountByAccountId(accountId));
    }

    /**
     * 禁用账号
     * @Author renshaorong
     * @Date 2021/5/25
     * @param accountId
     * @return
     */
    @PostMapping("disableByAccountId")
    public DataResponse disableByAccountId(@RequestParam("accountId") String accountId){
        return userAccountService.disableByAccountId(accountId) ? new DhResponse(ResponseCodeEnum.OK.getResponseCode()) : new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
    }


    /**
     * 启用账号
     * @Author renshaorong
     * @Date 2021/6/9
     * @param accountId
     * @return
     */
    @PostMapping("enableByAccountId")
    public DataResponse enableByAccountId(@RequestParam("accountId") String accountId){
        return userAccountService.enableByAccountId(accountId) ? new DhResponse(ResponseCodeEnum.OK.getResponseCode()) : new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
    }

    /***
     * @Description:添加用户账号
     * @Param: userAccountAddVO 账号以及用户信息参数
     * @Author: luojie
     * @Date: 2021/5/17 15:09
     */
    @PostMapping("/addUserAccountAndUserInfo")
    public DataResponse addUserAccountAndUserInfo(@RequestBody UserAccountAddQO userAccountAddQO){
        //如果是测试账号，邮箱不能为空
        if("1".equals(userAccountAddQO.getIfTestAccount())&&StringUtils.isBlank(userAccountAddQO.getUserEmail())){
            return new DhResponse(ResponseCodeEnum.USER_EMAIL_NOT_EMPTY.getResponseCode());
        }
        JSONObject result = userAccountService.addUserAccountAndUserInfo(userAccountAddQO);
        if(result.getBoolean("isExist")){
            return new DhResponse(ResponseCodeEnum.USER_ACCOUNT_IS_EXIST.getResponseCode());
        }else {
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        }
    }

    /**
     * 修改分机号
     * @Author pym
     * @Date  2021/5/26 15:46
     * @param accountId 账号ID
     * @param extensionNumber 分机号
     * @return {@link {com.crm.common.model.DataResponse}}
     */
    @PostMapping("/updateExtensionNumber")
    public DataResponse updateExtensionNumber(@RequestParam("accountId") String accountId,
                                              @RequestParam("extensionNumber") String extensionNumber){
        try {
            String message = userAccountService.updateExtensionNumber(accountId, extensionNumber);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), message);
        } catch (Exception e) {
            log.error("account updateExtensionNumber error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode(), "U000003");//修改分机号异常
        }
    }

    /**
     * 导入账号信息
     * @param request
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/importUserAccount")
    public DataResponse importUserAccount(HttpServletRequest request,
                                          @RequestParam MultipartFile file,
                                          @RequestParam String companyId,
                                          @RequestParam Integer type
    ) throws IOException {
        JSONObject jsonObject = new JSONObject();
        try {
            ExcelUtil excelUtil = new ExcelUtil();
            List<UserAccountImportVO> list = excelUtil.excelImport(file.getInputStream(), UserAccountImportVO.class);//1.读取前端的excel文件并转换成list集合
            if (list == null || list.size() == 0) {
                return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
            }
            jsonObject = userAccountService.importUserAccount(list,companyId,type);

        } catch (Exception e) {
            log.error("account importUserAccount:", e);
        }
        //返回导入数量、重复数量
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),jsonObject);
    }

    /**
     * 发送邮件告诉用户密码
     * @param companyId
     * @return
     */
    @GetMapping("sendUserPasswordToMail")
    public DataResponse sendUserPasswordToMail(String companyId){
        userAccountService.sendUserPasswordToMail(companyId);
        //返回导入数量、重复数量
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
    }

    /**
     * 把离职用户密码发送给公司总经理
     * @param companyId
     * @return
     */
    @GetMapping("sendLeaveUserPasswordToMail")
    public DataResponse sendLeaveUserPasswordToMail(String companyId,String sendMail){
        userAccountService.sendLeaveUserPasswordToMail(companyId,sendMail);
        //返回导入数量、重复数量
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
    }

    /**
     * 阶段性停用
     * @Author renshaorong
     * @Date 2021/6/24
     * @param accountId
     * @param deacType
     * @param deacToTime
     * @return
     */
    @PostMapping("saveDeacByAccountId")
    public DataResponse saveDeacByAccountId(String accountId, String deacType, String deacToTime){
        return userAccountService.saveDeacByAccountId(accountId,deacType,deacToTime) ? new DhResponse(ResponseCodeEnum.OK.getResponseCode()) : new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
    }


    /**
     * 离职
     * @Author renshaorong
     * @Date 2021/7/2
     * @param accountId
     * @return
     */
    @PostMapping("resignByAccountId")
    public DataResponse resignByAccountId(@RequestParam("accountId") String accountId){
        return userAccountService.resignByAccountId(accountId) ? new DhResponse(ResponseCodeEnum.OK.getResponseCode()) : new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
    }

    /**
     * 获取所有账号
     *
     * @param request
     * @return {@link {com.crm.common.model.DataResponse}}
     * @Author pym
     * @Date 2021/3/17 10:10
     */
    @GetMapping("/getList")
    public DataResponse getList(HttpServletRequest request) {
        Boolean rs = userAccountService.getList();
        if (rs) {
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        } else {
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /***
     * @Description:查询所有客服部人员列表
     * @Param:
     * @Author: luojie
     * @Date: 2021/11/9 14:33
     */
    @GetMapping("/selectReviewerList")
    public DataResponse selectReviewerList(HttpServletRequest request){
        List<JSONObject> jsonObject = userAccountService.selectReviewerList();
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),jsonObject);
    }

}
